package com.lovely3x.paymentlibrary.alipay;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.alipay.sdk.app.PayTask;
import com.lovely3x.common.managements.pay.IPayCallBack;
import com.lovely3x.common.managements.pay.InitHook;
import com.lovely3x.common.managements.pay.PayAction;
import com.lovely3x.common.managements.pay.PayRequest;
import com.lovely3x.common.managements.pay.PaymentManager;

import java.util.Map;

/**
 * Created by lovely3x on 17/3/21.
 */
public class AliPay2ServerSignAction implements PayAction, InitHook<PaymentManager> {

    public static final AliPay2ServerSignAction INSTANCE = new AliPay2ServerSignAction();

    private static final int SDK_PAY_FLAG = 1;

    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult2 payResult = new PayResult2((Map<String, String>) msg.obj);
                    //对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        PaymentManager.getInstance().notifyPayResult(IPayCallBack.PayMethod.AliPayServerSign, IPayCallBack.PayResult.Successful);
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        PaymentManager.getInstance().notifyPayResult(IPayCallBack.PayMethod.AliPayServerSign, IPayCallBack.PayResult.Fail);
                    }
                    break;
                }
            }
        }
    };

    @Override
    public void onInit(PaymentManager paymentManager) {
        paymentManager.registerPayAction(INSTANCE);
    }

    @Override
    public boolean pay(PayRequest payRequest, IPayCallBack.PayMethod payMethod) {
        if (payMethod == IPayCallBack.PayMethod.AliPayServerSign && payRequest instanceof AliPayPayRequest) {
            payForAliPay(((AliPayPayRequest) payRequest).mActivity, payRequest.getTn());
            return true;
        }
        return false;
    }

    private void payForAliPay(final Activity context, final String orderInfo) {
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(context);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }
}
